"use client";

import { useEffect, useState, useCallback, forwardRef, useImperativeHandle } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { 
  Maze, 
  PlayerPosition, 
  Direction, 
  generateMaze, 
  isValidMove, 
  movePlayer, 
  isAtEnd 
} from "./maze-generator";

type MazeProps = {
  width: number;
  height: number;
  cellSize: number;
  onComplete?: () => void;
  difficulty?: "easy" | "medium" | "hard";
};

export type MazeHandle = {
  maze: Maze;
  player: PlayerPosition;
  setPlayer: (position: PlayerPosition) => void;
  setBreadcrumbs: (fn: (prev: PlayerPosition[]) => PlayerPosition[]) => void;
  completed: boolean;
  setCompleted: (completed: boolean) => void;
  regenerateMaze: () => void;
};

export const MazeGame = forwardRef<MazeHandle, MazeProps>(({ 
  width, 
  height, 
  cellSize, 
  onComplete,
  difficulty = "medium"
}, ref) => {
  // 根据难度调整迷宫大小
  const getMazeSize = () => {
    switch(difficulty) {
      case "easy": return { w: 8, h: 8 };
      case "medium": return { w: 12, h: 12 };
      case "hard": return { w: 16, h: 16 };
      default: return { w: width, h: height };
    }
  };

  const { w, h } = getMazeSize();
  
  const [maze, setMaze] = useState<Maze>(generateMaze(w, h));
  const [player, setPlayer] = useState<PlayerPosition>({ x: maze.start.x, y: maze.start.y });
  const [breadcrumbs, setBreadcrumbs] = useState<PlayerPosition[]>([]);
  const [completed, setCompleted] = useState(false);
  const [wallColors, setWallColors] = useState<string[]>([
    "var(--primary)", 
    "var(--secondary)", 
    "var(--accent)"
  ]);

  // 重新生成迷宫
  const regenerateMaze = useCallback(() => {
    const newMaze = generateMaze(w, h);
    setMaze(newMaze);
    setPlayer({ x: newMaze.start.x, y: newMaze.start.y });
    setBreadcrumbs([]);
    setCompleted(false);
  }, [w, h]);

  // 处理键盘输入
  const handleKeyDown = useCallback((e: KeyboardEvent) => {
    if (completed) return;

    let direction: Direction | null = null;

    switch (e.key) {
      case "ArrowUp":
      case "w":
        direction = Direction.UP;
        break;
      case "ArrowRight":
      case "d":
        direction = Direction.RIGHT;
        break;
      case "ArrowDown":
      case "s":
        direction = Direction.DOWN;
        break;
      case "ArrowLeft":
      case "a":
        direction = Direction.LEFT;
        break;
    }

    if (direction !== null && isValidMove(maze, player, direction)) {
      setBreadcrumbs((prev) => [...prev, player]);
      const newPosition = movePlayer(player, direction!);
      setPlayer(newPosition);

      if (isAtEnd(newPosition, maze.end)) {
        setCompleted(true);
        onComplete?.();
      }
    }
  }, [maze, player, completed, onComplete]);

  // 循环变换墙壁颜色
  useEffect(() => {
    const interval = setInterval(() => {
      setWallColors((prev) => {
        const first = prev[0];
        return [...prev.slice(1), first];
      });
    }, 3000);
    return () => clearInterval(interval);
  }, []);

  // 添加键盘事件监听
  useEffect(() => {
    window.addEventListener("keydown", handleKeyDown);
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [handleKeyDown]);

  // 暴露内部状态和方法给父组件
  useImperativeHandle(ref, () => ({
    maze,
    player,
    setPlayer,
    setBreadcrumbs,
    completed,
    setCompleted,
    regenerateMaze,
    onComplete
  }), [maze, player, completed, regenerateMaze, onComplete]);

  return (
    <div className="flex flex-col items-center gap-4">
      <div 
        className="relative border-2 border-muted rounded-md overflow-hidden"
        style={{ 
          width: w * cellSize, 
          height: h * cellSize,
          background: "rgba(0,0,0,0.8)"
        }}
      >
        {/* 迷宫单元格 */}
        {maze.cells.map((row, y) =>
          row.map((cell, x) => (
            <div
              key={`${x}-${y}`}
              className="absolute"
              style={{
                left: x * cellSize,
                top: y * cellSize,
                width: cellSize,
                height: cellSize,
              }}
            >
              {/* 墙壁 */}
              {cell.walls.top && (
                <div
                  className="maze-wall absolute"
                  style={{
                    top: 0,
                    left: 0,
                    width: "100%",
                    height: "2px",
                    "--wall-color": wallColors[0]
                  } as React.CSSProperties}
                />
              )}
              {cell.walls.right && (
                <div
                  className="maze-wall absolute"
                  style={{
                    top: 0,
                    right: 0,
                    width: "2px",
                    height: "100%",
                    "--wall-color": wallColors[1]
                  } as React.CSSProperties}
                />
              )}
              {cell.walls.bottom && (
                <div
                  className="maze-wall absolute"
                  style={{
                    bottom: 0,
                    left: 0,
                    width: "100%",
                    height: "2px",
                    "--wall-color": wallColors[2]
                  } as React.CSSProperties}
                />
              )}
              {cell.walls.left && (
                <div
                  className="maze-wall absolute"
                  style={{
                    top: 0,
                    left: 0,
                    width: "2px",
                    height: "100%",
                    "--wall-color": wallColors[0]
                  } as React.CSSProperties}
                />
              )}

              {/* 起点 */}
              {x === maze.start.x && y === maze.start.y && (
                <div
                  className="maze-start absolute"
                  style={{
                    left: cellSize * 0.2,
                    top: cellSize * 0.2,
                    width: cellSize * 0.6,
                    height: cellSize * 0.6,
                    borderRadius: "50%",
                  }}
                />
              )}

              {/* 终点 */}
              {x === maze.end.x && y === maze.end.y && (
                <div
                  className="maze-end absolute"
                  style={{
                    left: cellSize * 0.2,
                    top: cellSize * 0.2,
                    width: cellSize * 0.6,
                    height: cellSize * 0.6,
                    borderRadius: "50%",
                  }}
                />
              )}

              {/* 面包屑 */}
              {breadcrumbs.some((pos) => pos.x === x && pos.y === y) && (
                <div
                  className="maze-breadcrumb absolute"
                  style={{
                    left: cellSize * 0.4,
                    top: cellSize * 0.4,
                    width: cellSize * 0.2,
                    height: cellSize * 0.2,
                    borderRadius: "50%",
                  }}
                />
              )}
            </div>
          ))
        )}

        {/* 玩家 */}
        <AnimatePresence>
          <motion.div
            key="player"
            className="maze-player absolute"
            initial={{ scale: 0 }}
            animate={{
              left: player.x * cellSize + cellSize * 0.25,
              top: player.y * cellSize + cellSize * 0.25,
              scale: 1,
            }}
            transition={{ type: "spring", damping: 15 }}
            style={{
              width: cellSize * 0.5,
              height: cellSize * 0.5,
            }}
          />
        </AnimatePresence>

        {/* 完成动画 */}
        <AnimatePresence>
          {completed && (
            <motion.div
              initial={{ scale: 0, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0, opacity: 0 }}
              className="absolute inset-0 flex items-center justify-center bg-black bg-opacity-70"
            >
              <motion.div
                className="text-4xl font-bold text-white neon-text"
                animate={{ scale: [1, 1.1, 1] }}
                transition={{ repeat: Infinity, duration: 2 }}
              >
                迷宫完成!
              </motion.div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>

      <div className="flex gap-4">
        <button
          onClick={regenerateMaze}
          className="px-4 py-2 bg-primary rounded-md hover:bg-opacity-80 transition-colors"
        >
          重新生成迷宫
        </button>
      </div>
    </div>
  );
});